package com.hjxr.quota.define.service.impl;

import cn.hutool.core.util.NetUtil;
import cn.hutool.system.SystemUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hjxr.quota.define.domain.QuotaReport;
import com.hjxr.quota.define.domain.QuotaValue;
import com.hjxr.quota.define.mapper.QuotaReportMapper;
import com.hjxr.quota.define.mapper.QuotaValueMapper;
import com.hjxr.quota.util.FileUtils;
import com.hjxr.quota.util.PageUtil;
import com.hjxr.quota.util.Query;
import com.hjxr.quota.util.SimpleFormulaAnalysis;
import com.hjxr.quota.define.service.IQuotaReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 报表表 服务实现类
 * </p>
 *
 * @author ma
 * @since 2020-10-16
 */
@Service
public class QuotaReportServiceImpl extends ServiceImpl<QuotaReportMapper, QuotaReport> implements IQuotaReportService {

    @Value("${hjxr.profile}")
    private String proFilePath;
    @Autowired
    private QuotaValueMapper quotaValueMapper;
    @Override
    public Integer fileInformationToDb(Map<String, String> params) {

        QuotaReport quotaReport = new QuotaReport();
        String name = params.get("name");
        quotaReport.setName(name);
        if(FileUtils.isContainChinese(name)){
            quotaReport.setUname("THEME_" + FileUtils.getPinYinHeadChar(name));
        }else{
            quotaReport.setUname(name);
        }
        quotaReport.setUrl(params.get("filePath"));
        quotaReport.setThemeSetId(Integer.valueOf(params.get("themeSetId")));
        quotaReport.setLable(params.get("lable"));
        quotaReport.setDescription("description");

        if(save(quotaReport)){
            return quotaReport.getId();
        }
        return 0;
    }

    @Transactional
    @Override
    public Boolean deleteFile(Integer id) {

        try {
            if(getById(id).getUrl()!=null){
                File myDelFile = new File(getById(id).getUrl());
                myDelFile.delete();
            }
            removeById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public PageUtil queryReportListByThemeId(Map<String, Object> params) {

        QueryWrapper<QuotaReport> wrapper = new QueryWrapper<>();
        String themeSetId = (String) params.get("THEME_SET_ID");
        if (StringUtils.isNotBlank(themeSetId)) {
            wrapper.eq("THEME_SET_ID", Integer.valueOf(themeSetId));
        }
        IPage<QuotaReport> page = this.page(
                new Query<QuotaReport>().getPage(params),
                wrapper
        );
        return new PageUtil(page);
    }

    @Override
    public PageUtil queryReportListByFileName(Map<String, Object> params) {
        QueryWrapper<QuotaReport> wrapper = new QueryWrapper<>();
        String fileName = (String) params.get("fileName");
        String themeId=(String) params.get("THEME_SET_ID");
        if(themeId!=null){
            if (StringUtils.isNotBlank(fileName)&&StringUtils.isNotBlank(themeId)) {
                wrapper.eq("THEME_SET_ID", Integer.valueOf(themeId));
                wrapper.like("NAME", fileName);
            }
        }else{
            if (StringUtils.isNotBlank(fileName)) {
                wrapper.like("NAME", fileName);
            }
        }
        IPage<QuotaReport> page = this.page(
                new Query<QuotaReport>().getPage(params),
                wrapper
        );
        return new PageUtil(page);
    }

    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）
    public final static String UPLOAD_PATH_PREFIX = "static/uploadFile/";

    @Override
//    public String fileUpload(MultipartFile file, HttpServletRequest request) {
//        if (file.isEmpty()) {
//            return "文件不存在";
//        }
//        try {
//            InputStream inputStream = file.getInputStream();
//            String fileName = file.getOriginalFilename();
//            //String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + format + newName;
//            String realPath = new String("src/main/resources/" + UPLOAD_PATH_PREFIX);
//
//            String finalName = System.currentTimeMillis() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
//            File dest = new File(file.getAbsolutePath() + File.separator + finalName);
//            if (!dest.getParentFile().exists()) {
//                dest.getParentFile().mkdirs();
//            }
//            try {
//                file.transferTo(dest);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return e.toString();
//            }
//
//            return finalName;
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            return e.toString();
//        }
//    }

    public String fileUpload(MultipartFile uploadFile, HttpServletRequest request){
        if(uploadFile.isEmpty()){
            //返回选择文件提示
            return "请选择上传文件";
        }
        String format = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
        String oldName = uploadFile.getOriginalFilename();
        String newName =System.currentTimeMillis() + "." + oldName.substring(oldName.lastIndexOf(".") + 1);
        //存放上传文件的文件夹
        File file = new File(proFilePath +"/"+ format+"/"+newName);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            uploadFile.transferTo(file);
            String ip = NetUtil.localIpv4s().stream().filter(item -> item.startsWith("20")).collect(Collectors.joining());
            String filePath = "http://"+ (StringUtils.isNotBlank(ip)?ip:SystemUtil.getHostInfo().getAddress()) + ":881/" + format +"/"+ newName;
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }

    @Override
    public Float computeValue(Map<String, Object> params) {
        Integer qId =(Integer)params.get("quotaId");//预指标id
        List<Integer> dimIdList =(List<Integer>)params.get("dimIdList");
        String type =(String)params.get("type");

        Float sumValue = 0f;
        Float value1 = 0f;//用于计算最大/最小值
        Integer count = 0;//用于计算计数/平均值
        //在指标值表查询此指标id指标列表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("QUOTA_ID", qId);
        List<QuotaValue> quotaValueList = quotaValueMapper.selectList(queryWrapper);
        if (quotaValueList.size() == 0) {
            return null;
        }
        for (QuotaValue quotaValue : quotaValueList) {
            String dimStr = quotaValue.getDimensions();
            List<String> strList1 = Arrays.asList(dimStr.split(",")).stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
            List<Integer> strList = strList1.stream().map((m) -> Integer.valueOf(m)).collect(Collectors.toList());
            if (strList.containsAll(dimIdList)) {//判断该维度列表是否包含共有维度列表
                if (type.equals("0")) {//根据指标值生成
                    if (quotaValue.getSm() != null) {
                        sumValue += quotaValue.getSm();
                    }
                } else if (type.equals("1")) {//根据最大值生成
                    if (quotaValue.getMx() != null) {
                        if (value1.compareTo(quotaValue.getMx()) == 1) {

                        } else {
                            value1 = quotaValue.getMx();
                        }
                    }
                } else if (type.equals("2")) {//根据最小值生成
                    if (quotaValue.getMn() != null) {
                        if (count == 0) {
                            value1 = quotaValue.getMn();
                            count++;
                        }
                        if (value1.compareTo(quotaValue.getMn()) == 1) {
                            value1 = quotaValue.getMn();
                        }
                    }
                } else if (type.equals("3")) {//根据计数生成
                    count++;
                } else if (type.equals("4")) {//根据平均值生成
                    count++;
                    if (quotaValue.getSm() != null) {
                        value1 += quotaValue.getSm();
                    }
                }
            }
        }
        switch (type) {
            case "0"://根据指标值生成
                return sumValue;
            case "1"://根据最大值生成
                return value1;
            case "2"://根据最小值生成
                return value1;
            case "3"://根据计数生成
                return (float) count;
            case "4"://根据平均值生成
                return (float) SimpleFormulaAnalysis.divide2(value1, count);
            default:
                return null;
        }
    }
}
